<template>
    <div class="panel-tab__content">
        <base-table
            ref="elementPropertyTable"
            :tableData="elementPropertyTableConfig.tableData"
            :tableHeader="elementPropertyTableConfig.tableHeader"
            :tableConfig="elementPropertyTableConfig.tableConfig"
        >
            <template slot-scope="{ scope }">
                <div v-if="scope.type === 'handle'">
                    <el-button
                        size="mini"
                        type="text"
                        @click="openAttributesForm(scope.row, scope.$index)"
                        >编辑</el-button
                    >
                    <el-divider direction="vertical" />
                    <el-button
                        size="mini"
                        type="text"
                        style="color: #ff4d4f"
                        @click="removeAttributes(scope.row, scope.$index)"
                        >移除</el-button
                    >
                </div>
            </template>
        </base-table>
        <div class="element-drawer__button">
            <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                @click="openAttributesForm(null, -1)"
                >添加属性</el-button
            >
        </div>

        <el-dialog
            :visible.sync="propertyFormModelVisible"
            title="属性配置"
            width="600px"
            append-to-body
            destroy-on-close
        >
            <base-form
                :formItems="propertyFormConfig.formItems"
                :formData="propertyFormConfig.formSubmit"
                :formConfig="propertyFormConfig.formConfig"
                ref="propertyForm"
            />
            <template slot="footer">
                <el-button size="mini" @click="propertyFormModelVisible = false"
                    >取 消</el-button
                >
                <el-button size="mini" type="primary" @click="saveAttribute"
                    >确 定</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@/components/baseTable/index'
import BaseForm from '@/components/baseForm/index'
export default {
    name: 'ElementProperties',
    components: {
        BaseTable,
        BaseForm
    },
    props: {
        id: String,
        type: String
    },
    inject: {
        prefix: 'prefix',
        width: 'width'
    },
    data() {
        return {
            elementPropertyTableConfig: {
                // 表格数据
                tableData: [],
                // 表格头数据
                tableHeader: [
                    {
                        type: 'index',
                        label: '序号',
                        width: 50,
                        visible: true
                    },
                    {
                        prop: 'name',
                        label: '属性值',
                        visible: true,
                        showOverflowTooltip: true
                    },
                    {
                        label: '操作',
                        type: 'handle',
                        visible: true
                    }
                ],
                // 表格配置
                tableConfig: {
                    border: true,
                    size: 'mini',
                    height: 'auto'
                }
            },
            // 注入的表单配置
            propertyFormConfig: {
                formItems: [
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入属性名',
                            label: '属性名',
                            prop: 'name',
                            width: 'w-1',
                            isShow: true
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入属性值',
                            label: '属性值',
                            prop: 'value',
                            width: 'w-1',
                            clearable: true,
                            isShow: true
                        }
                    ]
                ],
                formSubmit: {
                    //属性名
                    name: '',
                    // 属性值
                    value: ''
                },
                formConfig: {
                    labelPosition: 'left', // label对齐方式
                    labelWidth: '100px',
                    size: 'mini',
                    height: 'auto'
                }
            },
            propertyForm: {},
            editingPropertyIndex: -1,
            propertyFormModelVisible: false
        }
    },
    watch: {
        id: {
            immediate: true,
            handler(val) {
                val && val.length && this.resetAttributesList()
            }
        }
    },
    methods: {
        resetAttributesList() {
            this.bpmnElement = window.bpmnInstances.bpmnElement
            this.otherExtensionList = [] // 其他扩展配置
            this.bpmnElementProperties =
                this.bpmnElement.businessObject?.extensionElements?.values?.filter(
                    ex => {
                        if (ex.$type !== `${this.prefix}:Properties`) {
                            this.otherExtensionList.push(ex)
                        }
                        return ex.$type === `${this.prefix}:Properties`
                    }
                ) ?? []

            // 保存所有的 扩展属性字段
            this.bpmnElementPropertyList = this.bpmnElementProperties.reduce(
                (pre, current) => pre.concat(current.values),
                []
            )
            // 复制 显示
            this.elementPropertyTableConfig.tableData = JSON.parse(
                JSON.stringify(this.bpmnElementPropertyList ?? [])
            )
        },
        openAttributesForm(attr, index) {
            this.editingPropertyIndex = index
            this.propertyFormConfig.formSubmit =
                index === -1 ? {} : JSON.parse(JSON.stringify(attr))
            this.propertyFormModelVisible = true
            this.$nextTick(() => {
                if (this.$refs['attributeFormRef'])
                    this.$refs['attributeFormRef'].clearValidate()
            })
        },
        removeAttributes(attr, index) {
            this.$confirm('确认移除该属性吗？', '提示', {
                confirmButtonText: '确 认',
                cancelButtonText: '取 消'
            })
                .then(() => {
                    this.elementPropertyTableConfig.tableData.splice(index, 1)
                    this.bpmnElementPropertyList.splice(index, 1)
                    // 新建一个属性字段的保存列表
                    const propertiesObject = window.bpmnInstances.moddle.create(
                        `${this.prefix}:Properties`,
                        {
                            values: this.bpmnElementPropertyList
                        }
                    )
                    this.updateElementExtensions(propertiesObject)
                    this.resetAttributesList()
                })
                .catch(() => console.info('操作取消'))
        },
        /**
         * 保存配置
         */
        saveAttribute() {
            console.log(
                'window.bpmnInstances.modeling',
                window.bpmnInstances.modeling.updateModdleProperties
            )
            const { name, value } = this.propertyFormConfig.formSubmit
            console.log('this.editingPropertyIndex', this.editingPropertyIndex)
            if (this.editingPropertyIndex !== -1) {
                window.bpmnInstances.modeling.updateModdleProperties(
                    this.bpmnElement,
                    this.bpmnElementPropertyList[this.editingPropertyIndex],
                    {
                        name,
                        value
                    }
                )
            } else {
                // 新建属性字段
                const newPropertyObject = window.bpmnInstances.moddle.create(
                    `${this.prefix}:Property`,
                    { name, value }
                )
                // 新建一个属性字段的保存列表
                const propertiesObject = window.bpmnInstances.moddle.create(
                    `${this.prefix}:Properties`,
                    {
                        values: this.bpmnElementPropertyList.concat([
                            newPropertyObject
                        ])
                    }
                )
                this.updateElementExtensions(propertiesObject)
            }
            this.propertyFormModelVisible = false
            this.resetAttributesList()
        },
        updateElementExtensions(properties) {
            const extensions = window.bpmnInstances.moddle.create(
                'bpmn:ExtensionElements',
                {
                    values: this.otherExtensionList.concat([properties])
                }
            )
            window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
                extensionElements: extensions
            })
        }
    }
}
</script>
